use serde::{Deserialize, Serialize};
use std::fmt::Debug;

mod config;
pub use crate::config::Config;

mod gsearch;
pub use crate::gsearch::*;

mod chat;
pub use crate::chat::*;

#[derive(Default, Serialize, Deserialize, Debug, Clone)]
pub struct Task {  
    #[serde(default)]
    pub id: i32,
    #[serde(default)]
    pub name: String,    
    #[serde(default)]    
    pub timestamp: String,
    #[serde(default)]
    pub count: i32,    
}


/* 
pub async fn sqlite_db_init(pool: &SqlitePool) -> anyhow::Result<()> {
    let sql = r#"
    CREATE TABLE tasks(
        Id INTEGER PRIMARY KEY AUTOINCREMENT,
        Name  CHAR(10)  NOT NULL,       
        Name  CHAR(16),
        Timestamp  CHAR(8),        
        Count INTEGER DEFAULT 0              
        );"#;
    info!("{}", sql);    
    let affect_rows = sqlx::query(sql).execute(pool).await?;
    debug!("create table opens {:?}", affect_rows);    
    Ok(())
}


pub async fn new_task(pool: &SqlitePool, name: &str, ctime:&str, count:i32) -> anyhow::Result<i32> {
    let sql = "SELECT * FROM tasks WHERE Name=? limit 1";
    let rows = sqlx::query_as::<_, Task>(sql)
        .bind(name)
        .fetch_all(pool)
        .await?;   
    if rows.len() >= 1 {
        error!("cant open, already open id = {}", rows[0].id);
        return Ok(rows[0].id);
    }else{
        let cid =
        sqlx::query(r#"INSERT INTO tasks(Name, Timestamp, Count) VALUES (?,?,?)"#)
            .bind(name)                
            .bind(ctime)
            .bind(count)
            .execute(pool)
            .await?
            .last_insert_rowid();
        Ok(cid as i32)
    }    
}


pub async fn read_name_task(pool: &SqlitePool, name:&str) -> anyhow::Result< Vec<Task>> {
    let sql = "SELECT * FROM tasks WHERE Name=? ORDER BY Id Asc";
    let rows = sqlx::query_as::<_, Task>(sql)
        .bind(name)
        .fetch_all(pool)
        .await?;      
    Ok(rows)
}


pub async fn read_all_tasks(pool: &SqlitePool, limit:i32) -> anyhow::Result< Vec<Task>> {
    let sql = "SELECT * FROM tasks ORDER BY Id Asc LIMIT ?";
    let rows = sqlx::query_as::<_, Task>(sql)
        .bind(limit)
        .fetch_all(pool)
        .await?;      
    Ok(rows)
}
*/